const { notStrictEqual } = require('assert');
const fs = require('fs');

// 生成正弦波序列
const generateSineWave = (amplitude, period, sampleRate, length, offset=0) => {
  const sineWave = [];
  for (let i = 0; i < length; i++) {
    const t = i / sampleRate;
    const value = amplitude * Math.sin(3.5 * Math.PI * t / period + offset) + 0.5 * amplitude * Math.cos(2.7 * Math.PI * t / period);
    sineWave.push(value);
  }
  return sineWave;
};

// 生成均值为0，方差为100的正态分布随机数序列
const generateNormalRandoms = (length) => {
  const normalRandoms = [];
  for (let i = 0; i < length; i++) {
    let u = 0, v = 0;
    while (u === 0) u = Math.random(); //Converting [0,1) to (0,1)
    while (v === 0) v = Math.random();
    const randomValue = Math.sqrt(-2.0 * Math.log(u)) * Math.cos(2.0 * Math.PI * v);
    normalRandoms.push(randomValue * 10); // 生成均值为0，方差为100的正态分布随机数
  }
  return normalRandoms;
};

const generateNoiseSineWave = (length, channel=0) => {
  // 参数
  const amplitude = 100;
  const period = 2 * Math.PI;
  const sampleRate = 256 * (channel % 8 + 1);
  const threshold = 32767;
  // 生成正弦波形
  let sineWave = generateSineWave(amplitude, period, sampleRate, length, channel);

  // 生成均值为0，方差为100的正态分布随机数序列
  let normalRandoms = generateNormalRandoms(length);

  // 随机叠加正态分布的随机数到正弦波序列中
  for (let i = 0; i < length; i++) {
    let randomIndex = Math.floor(Math.random() * 32); // 随机间隔0-32个点加噪音
    let newIndex = i + randomIndex;
    if (newIndex < length) {
      let newValue = Math.floor(sineWave[newIndex] + 0.5 * normalRandoms[i]);
      if (newValue > threshold) {
        newValue = threshold;
      } else if (newValue < -threshold){
        newValue = -threshold;
      }
      sineWave[newIndex] = newValue;
    }
  }
  return sineWave;
}

csv_file = "sample_wave.csv"
bin_file = "sample_wave.dat"
const length = 10240*100;
const short_length = 10240;
const channel = 32;

const noiseSineWaves = [];
for (let ch = 0; ch < channel; ch++) {
  noiseSineWaves[ch] = generateNoiseSineWave(length, ch);
}

const framedWaves = [];
let k = 0;
for (let i = 0; i < length; i++) {
  for (let ch = 0; ch < channel; ch++) {
    framedWaves[k++] = noiseSineWaves[ch][i];
  }
}

// 将数据按每行N个整数的格式写入CSV文件
let csvData = '';
k=0;
for (let i = 0; i < short_length; i++) {
  for (let ch = 0; ch < channel; ch++) {
    if(ch<channel-1){
      csvData += (framedWaves[k++] + ',');
    }else{
      csvData += (framedWaves[k++] + '\n');
    }
  }
}

// 将数据写入文件
fs.writeFile(csv_file, csvData, (err) => {
  if (err) throw err;
  statsObj = fs.statSync(csv_file);
  console.log(`数据已写入到文件: ${csv_file}，文件大小 ${statsObj.size} 字节`);
});

// 创建一个Buffer来存储转换后的整型数
let buffer = Buffer.alloc(framedWaves.length * 2);

// 将浮点数转换为整型，并按小端存储到Buffer中
for (let i = 0; i < framedWaves.length; i++) {
  buffer.writeInt16LE(Math.floor(framedWaves[i]), i * 2); // Convert float to integer and write to buffer
  // buffer.writeFloatLE(Math.floor(framedWaves[i]), i * 4); // Convert float to integer and write to buffer
}

// 将Buffer写入到二进制文件中
fs.writeFile(bin_file, buffer, (err) => {
  if (err) throw err;
  statsObj = fs.statSync(bin_file); 
  console.log(`数据已写入到文件: ${bin_file}，文件大小 ${statsObj.size} 字节`);

  // 从二进制文件中读取信号
  fs.readFile(bin_file, (err, data) => {
    if (err) throw err;
    // 从Buffer中按小端读取整型数
    console.log(`读取二进制文件: ${bin_file}`);
    let k = 0;
    for (let i = 0; i < 10; i++) {
      let framedWavesIntegers = '';
      for (let ch = 0; ch < channel; ch++) {
        framedWavesIntegers += data.readInt16LE(k * 2) + ",";
        k++;
      }
      console.log(framedWavesIntegers + "\n");
    }
  });
});

